package com.eurasia.assignment.service;

import java.util.Optional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import com.eurasia.assignment.domain.User;
import com.eurasia.assignment.infrastructure.repository.UserRepository;

import lombok.RequiredArgsConstructor;

@Component
@RequiredArgsConstructor
public class SecurityContext {
    private static final Logger log = LoggerFactory.getLogger(SecurityContext.class);
    private final UserRepository userRepository;

    /**
     * 获取当前登录用户的用户名
     * @return 当前登录用户的用户名，如果未登录则返回null
     */
    public String getCurrentUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() && 
            !authentication.getPrincipal().equals("anonymousUser")) {
            return authentication.getName();
        }
        return null;
    }

    /**
     * 获取当前登录用户的完整User对象
     * @return 当前登录用户的User对象，如果未登录或用户不存在则返回null
     */
    public User getCurrentUser() {
        String username = getCurrentUsername();
        if (username != null) {
            try {
                Optional<User> userOpt = userRepository.findByUsername(username);
                return userOpt.orElse(null);
            } catch (Exception e) {
                log.error("获取当前用户信息失败: {}", e.getMessage());
            }
        }
        return null;
    }
}
